package 网络.文件上传;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
@SuppressWarnings("all")
public class fileUploadClient {
    public static void main(String[] args) throws IOException {
        //客户端连接服务端8888，得到Socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        String filePath = "/Users/anxiaodong/Downloads/jdk-8u301-linux-x64.tar.gz";
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));

        byte[] bytes = streamToByteArray(bufferedInputStream);

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(bytes);
        socket.shutdownOutput();//设置写入数据的结束标记

        //接受从服务单回复的消息
        InputStream inputStream = socket.getInputStream();
        String s = streamToString(inputStream);
        System.out.println(s);


        bufferedInputStream.close();
        bufferedOutputStream.close();
        socket.close();
    }

    //将输入流转成成byte[],即将文件的内容读入到字节数组中
    public static byte[] streamToByteArray(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) != -1){
            bs.write(b,0,len);
        }
        byte[] array = bs.toByteArray();
        bs.close();
        return array;
    }
    //将输入流转成String
    public static String streamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + "\r\n");
        }
        return stringBuffer.toString();
    }
}
